package com.stlm2.dems.service;

import com.stlm2.dems.dao.AddressDao;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.entity.Address;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;



import com.stlm2.dems.dao.*;
import com.stlm2.dems.entity.*;




import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;

import java.math.BigDecimal;

import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("purchaseOrderService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class PurchaseOrderService extends BaseServiceImpl<PurchaseOrder> {



	@Resource
	private UserDao userDao;
	@Resource
	private DdmGoodsDao ddmGoodsDao;

	@Resource
	private GoodSpecificationDao goodSpecificationDao;

	@Resource
	private AddressDao addressDao;

	@Resource
	private ValueAddedServicesDao valueAddedServicesDao;

	@Resource
	private GoodsValueAddedServicesDao goodsValueAddedServicesDao;
	@Resource
	private DdmShoppingCartDao ddmShoppingCartDao;
	@Resource
	private  PurchaseOrderDao purchaseOrderDao;
	@Resource
	private ShopOrderDao shopOrderDao;
	@Resource
	private GoodsOrderDao goodsOrderDao;
	@Resource
	private  UserCardsDao userCardsDao;

	@Override
	protected BaseDao<PurchaseOrder> getDao() {
		return purchaseOrderDao;
	}

	/*
   * sfy
   * 2017年10月24日09:33:10
   * 去结算、立即购买，生成一个商品清单
   * params type :1 立即购买  2 购物车去结算；orderInfor "[{},{}]"
   * */
	public Map<String, Object> preOrder(Integer type, String orderInfor, Integer userId) {
		Map<String, Object> map = new HashMap<String, Object>();// 最外层{} 01

		List<Map<String, Object>> goodsList = new ArrayList<Map<String, Object>>();//goodsList 所用{} 04





		BigDecimal addServicePirce = new BigDecimal(0); //增值服务的价格
		BigDecimal goodsPrice0 = new BigDecimal(0); //所有商品的价格
		BigDecimal goodPrice0 = new BigDecimal(0);//该商品的乘以其数量之后的价格
		BigDecimal specificationPrice = new BigDecimal(0);//规格的价格


		 /*
		 *  商品清单
		 * */

		//准备商品清单需要的容器

		if (type == 1) { //表示是立即购买的商
			//先判断是否传递过来要买的商品信息
			List<Map<String, Object>> addedServicesList = new ArrayList<Map<String, Object>>();
			if (StringUtils.isEmpty(orderInfor)) {
				map.put("code", 0);
				map.put("msg", "orderInfor不能为空");
				return map;
			}

			JSONArray jsonArray=null;
			try {
				 jsonArray = JSONArray.fromObject(orderInfor);//并将DS内容取出转为json数组
			}
			catch (Exception e){
                map.put("code",0);
				map.put("msg","orderInfor解析出错，请确认您的orderInfor格式正确");
				return  map;
			}
			for (int i = 0; i < jsonArray.size(); i++) {     //遍历json数组内容
				Map<String, Object> goodMap = new HashMap<String, Object>(); //good所用{} 05
				JSONObject object = jsonArray.getJSONObject(i);
				int goodId;
				Map<String, Object> goodServiceMap = new HashMap<String, Object>();// 一个商品和几个增值服务  08
               try {
				   goodId = object.getInt("goodId");
			   }catch (Exception e){
				   map.put("code",0);
				   map.put("msg","获取商品id异常");
				   return  map;
			   }
				int goodNum;
				try {
					goodNum = object.getInt("num");
				}
				catch (Exception e){
                  map.put("code",0);
					map.put("msg","获取商品数量出错");
					return  map;
				}
				if(goodNum<=0){
					map.put("code",0);
					map.put("msg","商品数量不能小于0或者等于0");
					return map;
				}

				int gooodSpecificationId = 0;

				BigDecimal goodsPrice = new BigDecimal(0);
				String addService = "";
				String propertiesName = "";
				try {
					gooodSpecificationId = object.getInt("goodSpecificationId");
				} catch (Exception e) {
					gooodSpecificationId = 0;//表示没有规格
				}
				try {
					addService = object.getString("addService");
				} catch (Exception e) {
					addService = "";
				}

				//处理商品清单
				//从数据库中获取商品对象
				DdmGoods good = ddmGoodsDao.getById(goodId);


				if (good == null) {
					map.put("code", 0);
					map.put("msg", "商品不存在");
					return map;
				}

					if (good.getState() == false) {
						map.put("code", 0);
						map.put("msg", "商品状态无效");
						map.put("msg", "无效商品");
						return map;
					}

					goodMap.put("goodName", good.getName());
					goodMap.put("imgUrl", good.getMainImg());
					//获取商品规格组合名称
					if (!StringUtils.isEmpty(gooodSpecificationId)&&gooodSpecificationId!=0) {
						GoodSpecification goodSpecification = goodSpecificationDao.getById(gooodSpecificationId);

						if(goodSpecification==null){
							map.put("code",0);
							map.put("msg","商品规格不存在");
							return map;
						}
						if(goodId!=goodSpecification.getGoodId()){
                          map.put("code",0);
							map.put("msg","商品和商品规格对象不一致");
							return  map ;

						}
						propertiesName = goodSpecification.getPropertiesName();
						BigDecimal a = goodSpecification.getMemberPrice().multiply(new BigDecimal(goodNum));
						specificationPrice = a.add(specificationPrice);
						goodMap.put("propertiesName", propertiesName);
						goodMap.put("goodsPrice", goodSpecification.getMemberPrice());
					} else {
						goodsPrice=good.getMemberPrice();  //计算价格以商品自身的价格为例
						goodPrice0 = good.getMemberPrice().multiply(new BigDecimal(goodNum));
						goodsPrice0= goodsPrice0.add(goodPrice0);
						goodMap.put("goodsPrice", goodsPrice);
					}

					goodMap.put("num", goodNum);


					goodServiceMap.put("good", goodMap); //将一个商品添加到商品与增值服务的map中

					//处理增值服务
					String[] arg = addService.split(",");
                   if(!StringUtils.isEmpty(addService)){
					   if(goodNum>1){
                              map.put("code",0);
						      map.put("msg","有增值服务的商品不能大于1个商品数量");
                                return  map;
					   }
					   for (int k = 0; k < arg.length; k++) {

						   Map<String, Object> addServiceMap = new HashMap<String, Object>();//  单个增值服务所用 07
						   int addServiceId = Integer.valueOf(arg[k]);
						   //获取增值服务对象
						   ValueAddedServices valueAddedService = valueAddedServicesDao.getById(addServiceId);
						   if(valueAddedService==null){
							   map.put("code",0);
							   map.put("msg","id为"+addServiceId+"的增值服务不存在");
                              return map;
						   }
						   //判断增值服务对象是否有有效
						   if (!valueAddedService.getState() == true) {
							   map.put("code",0);
							   map.put("msg","id为"+addServiceId+"的增值服务已经无效");
							   return  map;
						   }
                           /*
                           * 判断这些增值服务是否属于该商品可以拥有的增值服务
                           * */

					  /*
					  * 判断此增值服务是否属于该商品
					  * */
						   boolean flag = goodsValueAddedServicesDao.goodServiceMatch(goodId, valueAddedService.getId());
						   if (flag == false) {
							   map.put("code",0);
							   map.put("msg","商品id"+goodId+"与增值服务id为"+addServiceId+"不匹配");
							   return  map;

						   }
						   addServiceMap.put("name", valueAddedService.getName());
						   addServiceMap.put("time", valueAddedService.getWarrantyPeriod());
						   addServiceMap.put("price", valueAddedService.getPrice());
						   addServiceMap.put("url", valueAddedService.getDetailsUrl());
						addServicePirce=   addServicePirce.add(valueAddedService.getPrice());
						   addedServicesList.add(addServiceMap);
					   }

				   }

					goodServiceMap.put("addServices", addedServicesList);



				goodsList.add(goodServiceMap);
			}

		}else{ //购物去结算
              /*
              * 从数据库中获取用户购物车中选中要用来结算的商品
              * */
				List<DdmShoppingCart> cartList = ddmShoppingCartDao.getByUserId(userId);
				if (cartList == null || cartList.size() == 0) {//购物车中没有任何有效的商品数据
					map.put("code", 0);
					map.put("msg", "购物车为空");
					return map;
				}
		   /*
		   * 遍历购物车中的每一条记录
		   * */
				for (DdmShoppingCart ddmShoppingCart : cartList) {
					List<Map<String, Object>> addedServicesList = new ArrayList<Map<String, Object>>();
					Map<String, Object> goodMap = new HashMap<String, Object>(); //good所用{} 05
					int goodId = ddmShoppingCart.getGoodsId();
					int goodNum = ddmShoppingCart.getCount();
					int gooodSpecificationId = 0;
					try {
						gooodSpecificationId = ddmShoppingCart.getSpecificationId();
					} catch (Exception e) {
						gooodSpecificationId = 0;
					}

					String addService = "";
					addService = ddmShoppingCart.getValueAddedServicesIds();
					BigDecimal goodsPrice = new BigDecimal(0);
					String propertiesName = "";


					//处理商品清单
					//从数据库中获取商品对象
					DdmGoods good = ddmGoodsDao.getById(goodId);

					if (good == null) {
						map.put("code", 0);
						map.put("msg", "商品不存在");
						return map;
					}
					if (good.getState() == false) {
						map.put("code", 0);
						map.put("msg", "无效商品");
						return map;
					}

					goodMap.put("goodName", good.getName());
					Map<String, Object> goodServiceMap = new HashMap<String, Object>();// 一个商品和几个增值服务  08
					//获取商品规格组合名称
					if (!StringUtils.isEmpty(gooodSpecificationId) && gooodSpecificationId != 0) {
						GoodSpecification goodSpecification = goodSpecificationDao.getById(gooodSpecificationId);
						propertiesName = goodSpecification.getPropertiesName();
						BigDecimal a = goodSpecification.getMemberPrice().multiply(new BigDecimal(goodNum));
						specificationPrice = a.add(specificationPrice);
						goodMap.put("propertiesName", propertiesName);
						goodMap.put("goodsPrice",goodSpecification.getMemberPrice());
					} else {
						goodsPrice=good.getMemberPrice();  //计算价格以商品自身的价格为例
						goodPrice0 = good.getMemberPrice().multiply(new BigDecimal(goodNum));
						goodsPrice0= goodsPrice0.add(goodPrice0);

						goodMap.put("goodsPrice", goodsPrice);
					}

					goodMap.put("num", goodNum);
					goodMap.put("imgUrl", good.getMainImg());

					goodServiceMap.put("good", goodMap); //将一个商品添加到商品与增值服务的map中

					//处理增值服务
					if (!StringUtils.isEmpty(addService)) {
                       if(goodNum>1){
                         map.put("code",0);
						   map.put("msg","购物车中id:"+good.getId()+"的商品，因为有增值服务所以数量不能大于1");
                            return  map;
					   }
						String[] arg = addService.split(",");
						for (int k = 0; k < arg.length; k++) {
							Map<String, Object> addServiceMap = new HashMap<String, Object>();//  单个增值服务所用 07
							int addServiceId = Integer.valueOf(arg[k]);
							//获取增值服务对象
							ValueAddedServices valueAddedService = valueAddedServicesDao.getById(addServiceId);
							//判断增值服务对象是否有有效
							if (!valueAddedService.getState() == true) {
								continue;
							}
					  /*
					  * 判断此增值服务是否属于该商品
					  * */
							boolean flag = goodsValueAddedServicesDao.goodServiceMatch(goodId, valueAddedService.getId());
							if (flag == false) {
								continue;

							}
							addServiceMap.put("name", valueAddedService.getName());
							addServiceMap.put("time", valueAddedService.getWarrantyPeriod());
							addServiceMap.put("price", valueAddedService.getPrice());
							addServiceMap.put("url", valueAddedService.getDetailsUrl());
						addServicePirce=	addServicePirce.add(valueAddedService.getPrice());
							addedServicesList.add(addServiceMap);
						}



					}
					goodServiceMap.put("addServices", addedServicesList);
					goodsList.add(goodServiceMap);
				}
			}

          /*
          * 处理卡券相关 ，主要返回此用户可用的优惠券数量
          * */

			map.put("allPrice", addServicePirce.add(goodsPrice0).add(specificationPrice));
			map.put("goodsList", goodsList);
			map.put("code", 1);
			map.put("msg", "success");
			return map;
		}
	/*
	* 提交订单
	* */
	public void submitOrder(PurchaseOrder purchaseOrder,ShopOrder shopOrder,List<GoodsOrder> list,Integer type,List<DdmShoppingCart> cartList){
   /*
       * 数据库中添加3级订单2级订单一级订单
       * */
		purchaseOrderDao.add(purchaseOrder);
		shopOrderDao.add(shopOrder);
		for(GoodsOrder goodsOrder : list){
			goodsOrderDao.add(goodsOrder);
			/*
			* 处理卡券    更新使用的卡券的状态
			* */
           if(!StringUtils.isEmpty(goodsOrder.getCardId())){
               UserCards userCards = userCardsDao.getById(Integer.valueOf(goodsOrder.getCardId()));
			   if(userCards!=null){
                   //将卡券无效掉
				    userCards.setCardsState(CardsState.Used);
				    userCardsDao.modify(userCards);
			   }
		   }
		}
		/*
		* 将购物车的数据进行状态更新
		* */
		 if(type==2){
          for(DdmShoppingCart dcart:cartList){
              dcart.setShoppingCartState(ShoppingCartState.HaveAlreadyBought);//已经提交订单

		  }
		 }


	}

	/**
	 *  秒杀商品订单
	 * @param purchaseOrder
	 * @param shopOrder
	 * @param goodsOrder
	 */
	public void submitOrder(PurchaseOrder purchaseOrder,ShopOrder shopOrder,GoodsOrder goodsOrder){
   /*
       * 数据库中添加3级订单2级订单一级订单
       * */
		purchaseOrderDao.add(purchaseOrder);
		shopOrderDao.add(shopOrder);
		goodsOrderDao.add(goodsOrder);



	}

    public PurchaseOrder getByCode(String code) {
		return purchaseOrderDao.getByCode(code);
    }
}
